package com.two.screen.water.balance.net.api

import android.annotation.SuppressLint
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpHeaders
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.ObservableBody
import com.two.screen.water.balance.bean.BaseBean
import com.two.screen.water.balance.bean.water.*
import com.two.screen.water.balance.listener.ApiCallBack
import com.two.screen.water.balance.net.JsonConvert
import com.two.screen.water.balance.utils.*
import io.reactivex.Observable
import java.util.*


object NormalApi24 {
    val appUUid = CommUtils.getAppUUid()
    private fun getHeader(): HttpHeaders {
        return HttpHeaders().apply {
            put(Params.Authorization, DataApi.mSellerInfo?.access_token)
            put(Params.packageName, CommUtils.getPackageName())
            put(Params.deviceCode, appUUid)
        }
    }

    fun loginTelPwdSeller(params: SortedMap<String, Any?>, url: String?): Observable<BaseBean<SellerBean>> {
        return OkGo.post<BaseBean<SellerBean>>(url) //
            .upJson(CommUtils.gson.toJson(params))
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<SellerBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    fun loginTelPwdBuyer(params: SortedMap<String, String?>, url: String?): Observable<BaseBean<BuyerBean>> {
        return OkGo.get<BaseBean<BuyerBean>>(url) //
            .params(HttpParams().apply { put(params) })
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<BuyerBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }


    fun getProductBatch(ids: String?): Observable<BaseBean<MutableList<ProductBean>>> {
        return OkGo.get<BaseBean<MutableList<ProductBean>>>(Urls.getProductBatch + ids) //
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<MutableList<ProductBean>>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    /*提交订单*/
    fun putProductOrder(params: LocalOrderBean?, payType: Int, authCode: String? = null): Observable<BaseBean<PayResultBean>> {
        var detailList = params?.productList?.map {
            val detailMap = mutableMapOf(
                Params.productId to it.id,
                Params.productBatchId to it.batchId,
                Params.unitPrice to it.productUnitPrice,
                Params.grossWeight to it.roughWeight,
                Params.skinWeight to it.peelWeight,
            )
            //productSpecs：1定装(quantity)、2非定装(quantity、weight为主)、3散装(weight)
            if (ProductBean.isDingInstall(it.productSpecs)) {
                detailMap[Params.quantity] = it.netWeight
            }

            if (ProductBean.isNoDingInstall(it.productSpecs)) {
                detailMap[Params.weight] = it.netWeight
            }
            if (ProductBean.isSanInstall(it.productSpecs)) {
                detailMap[Params.weight] = it.netWeight
            }

            detailMap
        }
        val params = mapOf(
            Params.orderSource to "SCC",
            Params.tempOrderId to params?.hangId,
            Params.bazaarId to DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.id,
            Params.merchantId to DataApi.mSellerInfo?.merchantList?.firstOrNull()?.id,
            Params.deviceCode to appUUid,
            Params.buyerId to DataApi.mBuyerInfo?.id,
            Params.authCode to authCode,
            Params.status to 1,//0代客下单，1下单 就是帮客户创建订单 代课下单
            Params.discountMoney to 0,//接口需求，默认写死
            Params.payType to payType,
            Params.detailList to detailList
        )
        //TODO:这里需要转化数据
        return OkGo.post<BaseBean<PayResultBean>>(Urls.putProductOrder) //
            .upJson(CommUtils.gson.toJson(params))
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<PayResultBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    /*挂单*/
    fun putProductHang(params: LocalOrderBean?): Observable<BaseBean<NormalResultBean>> {
        var detailList = params?.productList?.map {
            val detailMap = mutableMapOf(
                Params.productId to it.id,
                Params.productBatchId to it.batchId,
                Params.unitPrice to it.productUnitPrice,
                Params.grossWeight to it.roughWeight,
                Params.skinWeight to it.peelWeight,
            )
            //productSpecs：1定装(quantity)、2非定装(quantity、weight为主)、3散装(weight)
            if (ProductBean.isDingInstall(it.productSpecs)) {
                detailMap[Params.quantity] = it.netWeight
            }
            if (ProductBean.isNoDingInstall(it.productSpecs)) {
                detailMap[Params.weight] = it.netWeight
            }
            if (ProductBean.isSanInstall(it.productSpecs)) {
                detailMap[Params.weight] = it.netWeight
            }
            detailMap
        }
        val params = mapOf(
            Params.bazaarId to DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.id,
            Params.merchantId to DataApi.mSellerInfo?.merchantList?.firstOrNull()?.id,
            Params.buyerId to DataApi.mBuyerInfo?.id,
            Params.detailList to detailList
        )
        return OkGo.post<BaseBean<NormalResultBean>>(Urls.putProductHang) //
            .upJson(CommUtils.gson.toJson(params))
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<NormalResultBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    /*删除挂单*/
    fun delProductHang(ids: String?): Observable<BaseBean<NormalResultBean>> {
        return OkGo.delete<BaseBean<NormalResultBean>>(Urls.delProductHang + ids) //
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<NormalResultBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    /*获取商品*/
    fun getProduct(): Observable<BaseBean<MutableList<ProductBean>>> {
        return OkGo.get<BaseBean<MutableList<ProductBean>>>(Urls.getProduct) //
            .params(HttpParams().apply {
                put(Params.bazaarId, DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.id)
                put(Params.merchantId, DataApi.mSellerInfo?.merchantList?.firstOrNull()?.id)
            })
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<MutableList<ProductBean>>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }


    /*获取公私秤，授权*/
    fun getDeviceInfo(): Observable<BaseBean<DeviceInfoBean>> {
        return OkGo.get<BaseBean<DeviceInfoBean>>(Urls.getDeviceInfo) //
            .params(HttpParams().apply {
                put(Params.code, appUUid)
            })
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<DeviceInfoBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    @SuppressLint("CheckResult")
    fun getOrderList(beginData: String?, endData: String?, mIsClickCollected: Boolean, apiCallBack: ApiCallBack) {
        OkGo.get<String>(if (mIsClickCollected) Urls.getOrderList01 else Urls.getOrderList02) //
            .params(HttpParams().apply {
                put(Params.beginDate, beginData)
                put(Params.endData, endData)
                put(Params.bazaarId, DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.id)
                put(Params.merchantId, DataApi.mSellerInfo?.merchantList?.firstOrNull()?.id)
            })
            .headers(getHeader())
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    var waterOrderBaseBean = try {
                        CommUtils.gson.fromJson(response?.body().toString(), WaterOrderBaseBean::class.java)
                    } catch (e: Exception) {
                        WaterOrderBaseBean().apply { msg = e.toString() }
                    }
                    if (waterOrderBaseBean.code != 200) {
                        ToastUtil.showToast(waterOrderBaseBean.msg ?: "查询失败!")
                        apiCallBack.fail(Throwable(waterOrderBaseBean.msg ?: "查询失败!"))
                        return
                    }
                    apiCallBack.success(waterOrderBaseBean)
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    apiCallBack.fail(response?.exception ?: Throwable("查询失败!"))
                    ToastUtil.showToast(response?.exception?.toString() ?: "查询失败!")
                }
            })
    }

    fun getOrderDetails(isClickCollected: Boolean, ids: String?): Observable<BaseBean<WaterOrderServerBean>> {
        return OkGo.get<BaseBean<WaterOrderServerBean>>((if (isClickCollected) Urls.getOrderDetails01 else Urls.getOrderDetails02) + ids) //
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<WaterOrderServerBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

    /*提交订单*/
    fun putWeightLog(newSelectedHadProductBean: ProductBean): Observable<BaseBean<PayResultBean>> {
        val params = mapOf(
            Params.bazaarId to DataApi.mSellerInfo?.bazaarList?.firstOrNull()?.id,
            Params.merchantId to DataApi.mSellerInfo?.merchantList?.firstOrNull()?.id,
            Params.deviceCode to appUUid,
            Params.productId to newSelectedHadProductBean.id,
            Params.weight to newSelectedHadProductBean.netWeight,
            Params.unitPrice to newSelectedHadProductBean.productUnitPrice,
            Params.money to newSelectedHadProductBean.subTotalPrice,
        )
        //TODO:这里需要转化数据
        return OkGo.post<BaseBean<PayResultBean>>(Urls.putWeightLog) //
            .upJson(CommUtils.gson.toJson(params))
            .headers(getHeader())
            .converter(object : JsonConvert<BaseBean<PayResultBean>>() {}) //
            .adapt(ObservableBody()) //
            .compose(RxUtils.io())
    }

}